package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckgroupCheckitemMapper;
import com.itheima.mapper.CheckitemMapper;
import com.itheima.pojo.CheckItem;
import com.itheima.service.CheckitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CheckitemServiceImpl implements CheckitemService {
    @Autowired
    private CheckitemMapper checkitemMapper;
    @Autowired
    private CheckgroupCheckitemMapper checkGroupCheckitemMapper;

    /**
     * 带条件分页查询
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult findPageWithQueryString(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<CheckItem> page = checkitemMapper.getByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增检查项
     * @param checkItem
     */
    @Override
    public void add(CheckItem checkItem) {
        checkitemMapper.add(checkItem);
    }

    /**
     * 根据id删除检查项
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        // 先检查该检查项是否有检查组关联
        Long count = checkGroupCheckitemMapper.findCountByCheckItemId(id);
        if (count > 0){
            // 有关联 不能删除
            throw new RuntimeException("该检查项与检查组有关联，不能删除");
        }
        // 没有关联，根据id删除检查项
        checkitemMapper.deleteById(id);
    }

    /**
     * 根据id查询检查项
     * @param id
     * @return
     */
    @Override
    public CheckItem findById(Integer id) {
        CheckItem checkItem = checkitemMapper.findById(id);
        return checkItem;
    }

    /**
     * 编辑检查项
     * @param checkItem
     */
    @Override
    public void edit(CheckItem checkItem) {
        checkitemMapper.edit(checkItem);
    }

    /**
     * 查询所有检查项
     * @return
     */
    @Override
    public List<CheckItem> findAll() {
        List<CheckItem> checkItems = checkitemMapper.findAll();
        return checkItems;
    }

    /**
     * 根据检查组id查询关联的检查项id
     * @param checkGroupId
     * @return
     */
    @Override
    public List<Integer> findCheckItemIdsByCheckGroupId(Integer checkGroupId) {
        List<Integer> checkItemIds = checkGroupCheckitemMapper.findCheckItemIdsByCheckGroupId(checkGroupId);
        return checkItemIds;
    }
}
